/*
https://leetcode-cn.com/problems/maximum-number-of-eaten-apples/solution/chi-ping-guo-de-zui-da-shu-mu-by-leetcod-93ka/
 */
import java.util.Comparator;
import java.util.PriorityQueue;

public class Solution1705 {
    public int eatenApples(int[] apples, int[] days) {
        int ans=0;
        PriorityQueue<int[]> queue=new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        for (int i=0;i<apples.length;i++){
            while (!queue.isEmpty() && queue.peek()[0]<=i){
                queue.poll();
            }
            if (apples[i]>0) {
                queue.offer(new int[]{i + days[i],apples[i]});
            }
            if (!queue.isEmpty()){
                int[] temp=queue.poll();
                ans++;
                if (temp[1]>1){
                    queue.offer(new int[]{temp[0],temp[1]-1});
                }
            }
        }
        int now=apples.length;
        while (!queue.isEmpty()){
            while (!queue.isEmpty() && queue.peek()[0]<=now){
                queue.poll();
            }
            if (queue.isEmpty()){
                break;
            }
            int[] temp=queue.poll();
            int t=Math.min(temp[1],temp[0]-now);
            ans+=t;
            now+=t;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1705().eatenApples(new int[]{1,2,3,5,2},new int[]{3,2,1,4,2}));
    }
}
